package es.index.util;

import java.lang.reflect.Method;

public final class ClassUtil {

	private ClassUtil() {
	}

	/**
	 * 完成反射操作，并根据properties中解析的字符串给对象赋值, 该反射是基于set，get实现的
	 * 
	 * @param t
	 * @param properties
	 * @return
	 */
	public static <T> T DynamicProperties(Class<T> t, String properties) {
		if (properties == null || properties.equals(""))
			return null;
		T object = null;
		try {
			object = t.newInstance();
			String[] arrs = properties.split(",");
			String[] items = null;
			String key = "";
			String value = "";
			for (int i = 0; i < arrs.length; i++) {
				arrs[i].trim();
				items = arrs[i].split("=");
				if (items.length > 0)
					key = items[0];
				if (items.length > 1)
					value = items[1];
				Method[] methods = t.getMethods();

				for (Method method : methods) {
					if (method.getName().startsWith("set" + key)) {
						try {
							Class<?>[] _parameterTypes = method.getParameterTypes();
							//boolean、byte、char、short、int、long、float 和 double。 
							//Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE
							if (_parameterTypes[0].equals(Integer.TYPE)) {
								method.invoke(object, Integer.parseInt(value));
							} else if(_parameterTypes[0].equals(Boolean.TYPE)) {
								method.invoke(object, Boolean.parseBoolean(value));
							} else if (_parameterTypes[0].equals(Byte.TYPE)) {
								method.invoke(object, Byte.parseByte(value));
							} else if (_parameterTypes[0].equals(Character.TYPE)) {
								method.invoke(object, value.charAt(0));
							} else if (_parameterTypes[0].equals(Short.TYPE)) {
								method.invoke(object, Short.parseShort(value));
							} else if (_parameterTypes[0].equals(Long.TYPE)) {
								method.invoke(object, Long.parseLong(value));
							} else if (_parameterTypes[0].equals(Float.TYPE)) {
								method.invoke(object, Float.parseFloat(value));
							} else if (_parameterTypes[0].equals(Double.TYPE)) {
								method.invoke(object, Double.parseDouble(value));
							} else if (_parameterTypes[0].equals(String.class)) {
								method.invoke(object, value);
							}
						} catch (Exception e) {
							System.out.println(e.toString() + ", 该类没有定义方法：" + "set" + key);
						}
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
}
